import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Search, Grid, Tree, TreeSelect,Feedback } from '@icedesign/base';
import './RolesTreeSelect.scss';
import axios from 'axios';
const { Node: TreeNode } = Tree;

export default class RolesTreeSelect extends Component {
  static displayName = 'RolesTreeSelect';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      value:[],
      expandedKeys: [],
      checkedKeys: [],
      type:null,
      code:null,
      checkStrictly:true,      
      autoExpandParent: true,
      treeData:[]
    };
  }

 
  componentDidMount() {
    let id = this.props.roleId;
    let type = this.props.type;
    let url = '';
    (type=='edit')?(url="/api/roles"+id):(url="/api/roles");
    this.getTreeData(url,type);

  }

  getTreeData =(url,type) =>{
    const matchedKeys = []; //节点数组，填充expandedkeys，展开所有节点
    const checkKeys = []; //checked节点数组，改变节点的选中状态
    const arr = [];
    axios.get(url).then((response)=>{
      if(response.data.success && response.data.code==200){
        let res = response.data.data[0];
        arr.push({id: res.id,text:'权限管理',disabled:true,data:{id:res.data.id},children:res.children}) //去除根节点，并保留其id
      
        this.setState({treeData:arr});
        loopKeys(arr)
        this.setState({
          checkedKeys: checkKeys,
          expandedKeys: matchedKeys,
          autoExpandParent: true
        });
      }else if(response.data.code == 401 && response.data.msg== '请登录!'){
        //登录过期/或未登录处理
        Feedback.toast.error(response.data.msg);
        setTimeout(()=>{
          hashHistory.push('/login');
        },3000) 
      }else{
        //其他错误，直接提示
        Feedback.toast.error(response.data.msg);
      }
      return ;
    }).catch((error)=>{
      //捕获异常
    Feedback.toast.error('数据读取失败，稍后再试！');
    return;
    });

    //取出所有节点keys值，展开所有节点
    const loopKeys = data =>
    data.forEach(item => {
      if (item.id) {
        matchedKeys.push(item.id+'code'+item.data.id);
      }
      if(item.checked){
        checkKeys.push(item.id+'code'+item.data.id)
      }
      if (item.children && item.children.length) {
        loopKeys(item.children);
      }
    });
    

  }

  handleChange=(value, data)=> {
    this.setState({
      value
    });
  }

  handleCheck(keys, info){
    this.setState({
      checkedKeys: keys
    });
    let keyCode = ''; //当前节点的id 即code
    let keyId = '';   //当前节点的data.id
    let Ids = [];     //为角色分配的权限的 id数组
    keys.forEach(item=>{
      keyCode = item.split('code')[0];
      keyId = item.split('code')[1];
      Ids.push({"id":keyId})
    })
    var newState = {
      id:[]
    }
    newState.id = Ids;
    this.props.onChange(newState)   //回掉函数传递参数给父组件 EditDialog
  };

  render() {
    const loop = data =>
    data.map(item => {
      return (
        //key值格式  code+"code"+id
          <TreeNode label={item.text} value={item.id+'code'+item.data.id} key={item.id+'code'+item.data.id} disabled={item.disabled} >
            {item.children && item.children.length ? loop(item.children) : null}
          </TreeNode>  
      );
    });
    return (
      
        <IceContainer
          className="filter-with-search-container"
          style={styles.filterWithSearchContainer}
        >
          <TreeSelect
            popupClassName="user-roles-tree"
            treeDefaultExpandAll
            treeCheckable
            value={this.state.checkedKeys}
            checkedKeys={this.state.checkedKeys}
            onChange={this.handleCheck.bind(this)}
            expandedKeys={this.state.expandedKeys}
            autoExpandParent={this.state.autoExpandParent}
            style={styles.treeSelect} >
            {loop(this.state.treeData)}
            </TreeSelect>
        </IceContainer>
    );
  }
}

const styles = {
  row: {
    alignItems: 'center',
  },
  filterContainer: {
    lineHeight: '32px',
  },
  filterItem: {
    height: '20px',
    padding: '0 20px',
    color: '#333',
    fontSize: '14px',
    cursor: 'pointer',
    borderRight: '1px solid #D8D8D8',
  },
  searchWrapper: {
    textAlign: 'right',
    margin: '10px 0',
  },
  treeSelect:{
    width:'100px'
  },
  treeNode:{
    height:"20px"
  }
};
